class RealDataFusion {
    constructor() {
        this.config = {
            exactMatchWeight: 0.4, // 降低精确匹配权重
            spatialWeight: 0.3, // 空间匹配权重
            semanticWeight: 0.3, // 语义匹配权重
            threshold: 0.5, // 降低匹配阈值
            spatialDistanceThreshold: 200, // 空间距离阈值(米)
        }
        this.results = []
        this.stats = {}
    }

    /**
     * 主要融合算法
     */
    fusionAlgorithm(spatialData, propertyData) {
        debugger
        console.log('🚀 开始真实数据融合...')
        console.log('空间数据数量:', spatialData.length)
        console.log('权属数据数量:', propertyData.length)

        const startTime = Date.now()

        // 数据预处理
        const processedSpatial = this.processSpatialData(spatialData)
        const processedProperty = this.processPropertyData(propertyData)

        console.log('处理后空间数据:', processedSpatial.length)
        console.log('处理后权属数据:', processedProperty.length)

        // 执行智能匹配
        const matches = this.performIntelligentMatching(
            processedSpatial,
            processedProperty
        )

        // 生成结果
        this.results = this.generateResults(
            matches,
            processedSpatial,
            processedProperty
        )

        // 计算统计
        this.calculateStats(Date.now() - startTime)

        console.log(`✅ 融合完成，匹配${this.results.length}对`)
        return this.results
    }

    /**
     * 处理空间数据 - 改进版
     */
    processSpatialData(data) {
        console.log('开始处理空间数据...')

        return data
            .filter(item => item.type === 'unit') // 只处理单元数据
            .map((item, index) => {
                const parsed = this.parseRoomId(item.fullRoomId)

                return {
                    id: `spatial_${index}`,
                    originalId: item.fullRoomId,
                    buildingId: parsed.building,
                    roomNumber: parsed.room,
                    floorNumber: this.extractFloor(parsed.room),
                    unitNumber: this.extractUnit(parsed.room),
                    community: parsed.community,
                    position: item.position,
                    area: this.calculateArea(item),
                    parsedInfo: parsed,
                    rawData: item,
                }
            })
            .filter(item => item.buildingId && item.roomNumber) // 过滤无效数据
    }

    /**
     * 处理权属数据 - 改进版
     */
    processPropertyData(data) {
        console.log('开始处理权属数据...')

        return data.map((item, index) => ({
            id: `property_${index}`,
            buildingNumber: this.normalizeBuildingNumber(item.buildingNumber),
            roomNumber: this.normalizeRoomNumber(item.roomNumber),
            floorNumber: item.floorNumber,
            unitNumber: item.unitNumber,
            fullRoomId: item.fullRoomId,
            community: item.community || '安滨嘉苑',
            ownerInfo: item.ownerInfo,
            propertyInfo: item.propertyInfo,
            coordinates: item.coordinates,
            rawData: item,
        }))
    }

    /**
     * 执行智能匹配 - 多层次匹配策略
     */
    performIntelligentMatching(spatialData, propertyData) {
        console.log('开始执行智能匹配...')

        const matches = []
        const matchStrategies = [
            this.exactMatch.bind(this),
            this.buildingRoomMatch.bind(this),
            this.fuzzyTextMatch.bind(this),
            this.spatialProximityMatch.bind(this),
        ]

        spatialData.forEach((spatial, spatialIndex) => {
            let bestMatch = null
            let bestScore = 0
            let usedStrategy = ''


            propertyData.forEach((property,propertyIndex) => {
                // 尝试多种匹配策略
                for (let i = 0; i < matchStrategies.length; i++) {
                    const score = matchStrategies[i](spatial, property)
                    console.log(
                        `匹配策略：${matchStrategies[i].name}，得分：${score}`
                    )
                    if (score > bestScore && score >= this.config.threshold) {
                        bestScore = score
                        bestMatch = {
                            ...property,
                            spatialIndex,
                            propertyIndex,
                            similarity: score,
                            confidence: score,
                            strategy: [
                                '精确匹配',
                                '建筑房号匹配',
                                '模糊文本匹配',
                                '空间邻近匹配',
                            ][i],
                        }
                        usedStrategy = bestMatch.strategy
                    }
                }
            })

            if (bestMatch) {
                matches.push(bestMatch)
            } else {
                console.log(`❌ 匹配失败: ${spatial.originalId}`)
            }
        })
        debugger
        // 去重处理 - 确保一对一匹配
        return this.deduplicateMatches(matches)
    }

    /**
     * 精确匹配
     */
    exactMatch(spatial, property) {
        console.log(`开始精确匹配: ${spatial}`)
        console.log(`目标房屋: ${property}`)

        debugger
        if (spatial.originalId === property.fullRoomId) {
            return 1.0
        }
        return 0
    }

    /**
     * 建筑+房号匹配
     */
    buildingRoomMatch(spatial, property) {
        let score = 0

        // 建筑匹配 (40%)
        if (this.isBuildingMatch(spatial.buildingId, property.buildingNumber)) {
            score += 0.4
        }

        // 房号匹配 (40%)
        if (this.isRoomMatch(spatial.roomNumber, property.roomNumber)) {
            score += 0.4
        }

        // 楼层匹配 (20%)
        if (
            spatial.floorNumber &&
            property.floorNumber &&
            spatial.floorNumber === property.floorNumber
        ) {
            score += 0.2
        }

        return score
    }

    /**
     * 模糊文本匹配
     */
    fuzzyTextMatch(spatial, property) {
        const spatialText = this.generateSearchText(spatial)
        const propertyText = this.generateSearchText(property)

        return this.calculateTextSimilarity(spatialText, propertyText)
    }

    /**
     * 空间邻近匹配
     */
    spatialProximityMatch(spatial, property) {
        debugger
        if (!spatial.position || !property.coordinates) {
            return 0
        }

        const distance = this.calculateDistance(
            spatial.position,
            property.coordinates
        )

        if (distance < this.config.spatialDistanceThreshold) {
            return Math.max(
                0,
                1 - distance / this.config.spatialDistanceThreshold
            )
        }

        return 0
    }

    /**
     * 建筑号匹配判断
     */
    isBuildingMatch(building1, building2) {
        if (!building1 || !building2) return false

        const normalized1 = this.normalizeBuildingNumber(building1)
        const normalized2 = this.normalizeBuildingNumber(building2)

        return normalized1 === normalized2
    }

    /**
     * 房号匹配判断
     */
    isRoomMatch(room1, room2) {
        if (!room1 || !room2) return false

        const normalized1 = this.normalizeRoomNumber(room1)
        const normalized2 = this.normalizeRoomNumber(room2)

        return normalized1 === normalized2
    }

    /**
     * 标准化建筑号
     */
    normalizeBuildingNumber(building) {
        if (!building) return ''

        return building.toString().toUpperCase().replace(/[^\w]/g, '') // 移除非字母数字字符
    }

    /**
     * 标准化房间号
     */
    normalizeRoomNumber(room) {
        if (!room) return ''

        return room.toString().replace(/[^\d]/g, '') // 只保留数字
    }

    /**
     * 生成搜索文本
     */
    generateSearchText(data) {
        const parts = []

        if (data.community) parts.push(data.community)
        if (data.buildingId || data.buildingNumber)
            parts.push(data.buildingId || data.buildingNumber)
        if (data.roomNumber) parts.push(data.roomNumber)

        return parts.join('-').toLowerCase()
    }

    /**
     * 计算文本相似度
     */
    calculateTextSimilarity(text1, text2) {
        if (!text1 || !text2) return 0

        // 简单的编辑距离算法
        const len1 = text1.length
        const len2 = text2.length
        const maxLen = Math.max(len1, len2)

        if (maxLen === 0) return 1

        // 计算相同字符的比例
        let matches = 0
        const minLen = Math.min(len1, len2)

        for (let i = 0; i < minLen; i++) {
            if (text1[i] === text2[i]) {
                matches++
            }
        }

        return matches / maxLen
    }

    /**
     * 去重匹配结果
     */
    deduplicateMatches(matches) {
        // 按相似度排序
        matches.sort((a, b) => b.similarity - a.similarity)

        const finalMatches = []
        const usedSpatial = new Set()
        const usedProperty = new Set()

        matches.forEach(match => {
            if (
                !usedSpatial.has(match.spatialIndex) &&
                !usedProperty.has(match.propertyIndex)
            ) {
                finalMatches.push(match)
                usedSpatial.add(match.spatialIndex)
                usedProperty.add(match.propertyIndex)
            }
        })

        return finalMatches
    }

    /**
     * 解析房屋ID - 改进版
     */
    parseRoomId(id) {
        if (!id) return { community: '安滨嘉苑', building: 'D1', room: '101' }

        const parts = id.split('-')
        if (parts.length >= 3) {
            return {
                community: parts[0] || '安滨嘉苑',
                building: parts[1] || 'D1',
                room: parts[2] || '101',
            }
        }

        // 兜底处理
        return { community: '安滨嘉苑', building: 'D1', room: '101' }
    }

    /**
     * 提取楼层号
     */
    extractFloor(roomNumber) {
        if (!roomNumber) return null

        const room = roomNumber.toString()
        if (room.length >= 2) {
            return parseInt(room.slice(0, -2)) || null
        }
        return null
    }

    /**
     * 提取单元号
     */
    extractUnit(roomNumber) {
        if (!roomNumber) return null

        const room = roomNumber.toString()
        if (room.length >= 1) {
            return parseInt(room.slice(-1)) || null
        }
        return null
    }

    /**
     * 计算面积
     */
    calculateArea(item) {
        if (item.dimensions) {
            return item.dimensions.length * item.dimensions.width
        }
        return 85 + Math.random() * 30 // 默认85-115平米
    }

    /**
     * 计算地理距离 (Haversine公式)
     */
    calculateDistance(pos1, pos2) {
        const R = 6371000 // 地球半径(米)
        const lat1 = (pos1.latitude * Math.PI) / 180
        const lat2 = (pos2.latitude * Math.PI) / 180
        const deltaLat = ((pos2.latitude - pos1.latitude) * Math.PI) / 180
        const deltaLon = ((pos2.longitude - pos1.longitude) * Math.PI) / 180

        const a =
            Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
            Math.cos(lat1) *
                Math.cos(lat2) *
                Math.sin(deltaLon / 2) *
                Math.sin(deltaLon / 2)
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))

        return R * c
    }

    /**
     * 生成结果
     */
    generateResults(matches, spatialData, propertyData) {
        return matches.map((match, index) => {
            const spatialItem = spatialData[match.spatialIndex]
            const propertyItem = propertyData[match.propertyIndex]

            return {
                matchId: `match_${index}`,
                confidence: match.confidence,
                matchStrategy: match.strategy,
                spatialData: {
                    fullRoomId: spatialItem.originalId,
                    roomId: spatialItem.originalId,
                    buildingId: spatialItem.buildingId,
                    roomNumber: spatialItem.roomNumber,
                    position: spatialItem.position,
                    area: spatialItem.area,
                    ...spatialItem,
                },
                propertyData: propertyItem,
                fusionQuality: {
                    spatialSimilarity: match.similarity,
                    semanticSimilarity: match.similarity,
                    attributeSimilarity: match.similarity,
                    overallSimilarity: match.similarity,
                },
            }
        })
    }

    /**
     * 计算统计信息
     */
    calculateStats(executionTime) {
        const totalMatches = this.results.length
        const avgConfidence =
            totalMatches > 0
                ? this.results.reduce((sum, r) => sum + r.confidence, 0) /
                  totalMatches
                : 0

        this.stats = {
            totalMatches,
            averageConfidence: avgConfidence,
            executionTime,
            qualityDistribution: {
                high: this.results.filter(r => r.confidence >= 0.8).length,
                medium: this.results.filter(
                    r => r.confidence >= 0.6 && r.confidence < 0.8
                ).length,
                low: this.results.filter(r => r.confidence < 0.6).length,
            },
        }
    }

    /**
     * 获取融合统计
     */
    getFusionStatistics() {
        return this.stats
    }

    /**
     * 导出结果
     */
    exportResults() {
        return {
            filename: `fusion_results_${new Date()
                .toISOString()
                .replace(/[:.]/g, '-')}.json`,
            data: JSON.stringify(
                {
                    results: this.results,
                    statistics: this.stats,
                    config: this.config,
                },
                null,
                2
            ),
        }
    }
}
